package com.ruoyi.parcel.util;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponseBody;
import darabonba.core.client.ClientOverrideConfiguration;
//import org.example.entity.model.AliyunSmsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

@Component
public class AliyunSmsUtil {

    @Autowired
    private AliyunSmsConfig aliyunSmsConfig;

    /**
     * 使用AK&SK初始化账号Client
     * @return Client 阿里云短信客户端
     */
    private AsyncClient createClient() {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(aliyunSmsConfig.getAccessKey())
                .accessKeySecret(aliyunSmsConfig.getAccessKeySecret())
                .build());

        AsyncClient client = AsyncClient.builder()
                .region(aliyunSmsConfig.getRegionId())
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create().setEndpointOverride(aliyunSmsConfig.getEndpoint())
                )
                .build();

        return client;
    }

    /**
     * 发送短信验证码
     * @param phoneNumber 手机号
     * @param pick_up_code 验证码
     * @return 结果信息. 短信验证码
     */
    public  String sendSms(String phoneNumber, String pick_up_code) {
        aliyunSmsConfig.setSignName("柜机管理");
        aliyunSmsConfig.setTemplateCode("SMS_475565177");
        //创建短信的模版
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phoneNumber)
                .signName(aliyunSmsConfig.getSignName())
                .templateCode(aliyunSmsConfig.getTemplateCode())
                .templateParam("{\"pick_up_code\":\"" + pick_up_code + "\"}")
                .build();
        try {
            System.out.println(sendSmsRequest.getSignName());
            AsyncClient client = createClient();
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            SendSmsResponseBody body = response.get().getBody();
            System.out.println(body.getMessage());
            System.out.println(body.getCode());
            //如果返回OK，则表示发送成功
            return body.getMessage();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

